package com.mf.common.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

/**
 * XML工具类
 * User: zhaoming
 * Date: 2016-06-04
 * To change this template use File | Settings | File Templates.
 **/
public class XMLUtils {



    /**
     * 格式化XML文件
     * @param xml
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static String formatXml(String xml) throws DocumentException, IOException {

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes()));
        //创建输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //制定输出xml的编码类型
        format.setEncoding("utf-8");

        StringWriter writer = new StringWriter();
        //创建一个文件输出流
        XMLWriter xmlwriter = new XMLWriter( writer, format );
        //将格式化后的xml串写入到文件
        xmlwriter.write(document);
        String returnValue = writer.toString();
        writer.close();

        //返回编译后的字符串格式
        return returnValue;
    }

    /**
     * 格式化XML文件
     * @param inputStream
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static String formatXml(InputStream inputStream) throws DocumentException, IOException {

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(inputStream);
        //创建输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //制定输出xml的编码类型
        format.setEncoding("utf-8");

        StringWriter writer = new StringWriter();
        //创建一个文件输出流
        XMLWriter xmlwriter = new XMLWriter( writer, format );
        //将格式化后的xml串写入到文件
        xmlwriter.write(document);
        String returnValue = writer.toString();
        writer.close();

        //返回编译后的字符串格式
        return returnValue;
    }
}
